﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
//-------------------------
using DotNetNuke.Entities.Modules;
using DotNetNuke.UI.Utilities;
using System.Collections.Generic;

namespace VluSDCEvent
{
    public partial class CtrEventEdit : PortalModuleBase
    {
        #region Members *****************************************
        VluSDCEvent.Controller oCtrler;
        string sLanguage;
        #endregion Members --------------------------------------

        #region Programmer Methods *****************************************
        bool MtdCheckDateValid()
        {
            string[] aFromDate = txtFromDate.Text.Split('/');
            string[] aToDate = txtToDate.Text.Split('/');
            // Get date format of Current Culture.
            List<int> lstIndex = Controller.MtdGetIndexDateFormat();

            bool bValid = false;
            // Compare year.
            int iFromDate = int.Parse(aFromDate[lstIndex.ElementAt(2)]);
            int iToDate = int.Parse(aToDate[lstIndex.ElementAt(2)]);
            if (iFromDate == iToDate)
            {
                // Compare month.
                iFromDate = int.Parse(aFromDate[lstIndex.ElementAt(1)]);
                iToDate = int.Parse(aToDate[lstIndex.ElementAt(1)]);
                if (iFromDate == iToDate)
                {
                    // Compare day.
                    iFromDate = int.Parse(aFromDate[lstIndex.ElementAt(0)]);
                    iToDate = int.Parse(aToDate[lstIndex.ElementAt(0)]);
                    bValid = iFromDate <= iToDate;
                }
                else
                    bValid = iFromDate < iToDate;
            }
            else
                bValid = iFromDate < iToDate;
            if (!bValid)
                lblError.Text = "Lỗi ngày tháng";
            return bValid;
        }

        bool MtdCheckValid()
        {
            return MtdCheckDateValid();
        }

        void MtdGetControlValues(TblSDCEvent pEvent)
        {
            string[] aFromDate = txtFromDate.Text.Split('/');
            string[] aToDate = txtToDate.Text.Split('/');
            // Get date format of Current Culture.
            List<int> lstIndex = Controller.MtdGetIndexDateFormat();

            pEvent.StartDate = new DateTime(int.Parse(aFromDate[lstIndex.ElementAt(2)]), int.Parse(aFromDate[lstIndex.ElementAt(1)]), int.Parse(aFromDate[lstIndex.ElementAt(0)]));
            pEvent.EndDate = new DateTime(int.Parse(aToDate[lstIndex.ElementAt(2)]), int.Parse(aToDate[lstIndex.ElementAt(1)]), int.Parse(aToDate[lstIndex.ElementAt(0)]));
            pEvent.Content = txtContent.Text;
            // Thêm.
            pEvent.ModifiedBy = UserInfo.Username;
            pEvent.ModifiedTime = oCtrler.MtdGetDate();
        }
        
        void MtdSetControlValues(TblSDCEvent pEvent)
        {
            txtFromDate.Text = pEvent.StartDate.Value.ToShortDateString();
            txtToDate.Text = pEvent.EndDate.Value.ToShortDateString();
            if (pEvent.Content == null)
                txtContent.RichText.Text = string.Empty;
            else
                txtContent.Text = Server.HtmlDecode(pEvent.Content);
        }

        void MtdResetControl()
        {
            TblSDCEvent oEvent = new TblSDCEvent();
            oEvent.StartDate = oCtrler.MtdGetDate().Date;
            oEvent.EndDate = oEvent.StartDate;
            MtdSetControlValues(oEvent);
            lblEventId.Text = "0";
        }

        List<TblSDCEvent> MtdGetEventList()
        {
            List<TblSDCEvent> lstEvent = new List<TblSDCEvent>();
            // Lấy phần tử con cuối cùng.
            TblSDCEvent oEvent =
                (from Eves in oCtrler.OLinqData.TblSDCEvents
                 where Eves.IsDelete == false
                 && Eves.ChildId == null
                 && Eves.ModuleDefID == oCtrler.MtdGetModuleDefId((this.Parent.Parent as PortalModuleBase).ModuleId, this.TabId)
                 select Eves).FirstOrDefault();
            if (oEvent != null)
            {
                lstEvent.Add(oEvent);
                // Lặp lại cho mỗi cha.
                TblSDCEvent oEventParent =
                    (from Eves in oCtrler.OLinqData.TblSDCEvents
                     where Eves.IsDelete == false
                     && Eves.ChildId == oEvent.Id
                     && Eves.ModuleDefID == oCtrler.MtdGetModuleDefId((this.Parent.Parent as PortalModuleBase).ModuleId, this.TabId)
                     select Eves).FirstOrDefault();
                while (oEventParent != null)
                {
                    lstEvent.Add(oEventParent);
                    oEventParent =
                        (from Eves in oCtrler.OLinqData.TblSDCEvents
                         where Eves.IsDelete == false
                         && Eves.ChildId == oEventParent.Id
                         && Eves.ModuleDefID == oCtrler.MtdGetModuleDefId((this.Parent.Parent as PortalModuleBase).ModuleId, this.TabId)
                         select Eves).FirstOrDefault();
                }
            }
            else
                return null;
            return lstEvent;
        }

        void MtdMoveUp(int pId)
        {
            TblSDCEvent oEventParent =
                (from Eves in oCtrler.OLinqData.TblSDCEvents
                 where Eves.ChildId == pId
                 && Eves.ModuleDefID == oCtrler.MtdGetModuleDefId((this.Parent.Parent as PortalModuleBase).ModuleId, this.TabId)
                 select Eves).FirstOrDefault();
            if (oEventParent != null)
            {
                TblSDCEvent oEvent =
                   (from Eves in oCtrler.OLinqData.TblSDCEvents
                    where Eves.IsDelete == false
                    && Eves.Id == pId
                    && Eves.ModuleDefID == oCtrler.MtdGetModuleDefId((this.Parent.Parent as PortalModuleBase).ModuleId, this.TabId)
                    select Eves).FirstOrDefault();
                oEventParent.ChildId = oEvent.ChildId;
                TblSDCEvent oEventGrand =
                 (from Eves in oCtrler.OLinqData.TblSDCEvents
                  where Eves.ChildId == oEventParent.Id
                  && Eves.ModuleDefID == oCtrler.MtdGetModuleDefId((this.Parent.Parent as PortalModuleBase).ModuleId, this.TabId)
                  select Eves).FirstOrDefault();
                if (oEventGrand != null)
                {
                    oEventGrand.ChildId = oEvent.Id;
                }
                oEvent.ChildId = oEventParent.Id;
                oCtrler.OLinqData.SubmitChanges();
            }
        }
        #endregion Programmer Methods --------------------------------------

        #region Dotnet Methods *****************************************
        protected void Page_Init(object sender, EventArgs e)
        {
            sLanguage = (Page as DotNetNuke.Framework.PageBase).PageCulture.Name;
            //System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.FullDateTimePattern;
            string pathFrom = DotNetNuke.Common.Utilities.Calendar.InvokePopupCal(txtFromDate);
            CalendarImageFrom.Attributes.Add("OnClick", pathFrom);
            string pathTo = DotNetNuke.Common.Utilities.Calendar.InvokePopupCal(txtToDate);
            CalendarImageTo.Attributes.Add("OnClick", pathTo);


            //string jQueryPath = "~/Resources/Shared/scripts/jquery/jquery.min.js";
            //ClientAPI.RegisterClientScriptBlock(this.Page, "jQuery.js", "<script src=" + ResolveUrl(jQueryPath) + "></script>");
            //ClientAPI.RegisterStartUpScript(this.Page, "", "<script type=\"text/javascript\">jQuery.noConflict();</script>");
            ////Page.ClientScript.RegisterClientScriptInclude("datepicker", ModulePath + "js/ui.datepicker." + sLanguage + ".js");

            oCtrler = new VluSDCEvent.Controller();

            cmbSave.Click += new EventHandler(cmbSave_Click);
            cmbCancel.Click += new EventHandler(cmbCancel_Click);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string sEventId = VluSDCEvent.Controller.MtdGetUrlParam(this.Request, "EventId");
                if (string.IsNullOrEmpty(sEventId))
                {
                    DateTime dt = oCtrler.MtdGetDate().Date;
                    txtFromDate.Text = dt.ToShortDateString();
                    txtToDate.Text = txtFromDate.Text;
                }
                else
                {
                    lblEventId.Text = sEventId;
                    TblSDCEvent oEvent =
                        (from eves in oCtrler.OLinqData.TblSDCEvents
                         where eves.IsDelete == false
                         && eves.Id.ToString() == sEventId
                         && eves.ModuleDefID == oCtrler.MtdGetModuleDefId((this.Parent.Parent as PortalModuleBase).ModuleId, this.TabId)
                         select eves).FirstOrDefault();
                    if (oEvent != null)
                        MtdSetControlValues(oEvent);
                }
                dgrEvent.DataSource = MtdGetEventList();
                dgrEvent.DataBind();
            }
        }

        void cmbSave_Click(object sender, EventArgs e)
        {
            // Không label lỗi.
            if (!(lblError.Visible = !MtdCheckValid()))
            {
                // Tạo mới.
                if (lblEventId.Text == "0")
                {
                    TblSDCEvent oEvent = new TblSDCEvent();
                    oEvent.ModuleDefID = oCtrler.MtdGetModuleDefId((this.Parent.Parent as PortalModuleBase).ModuleId, this.TabId);
                    oEvent.CreateBy = UserInfo.Username;
                    oEvent.CreateTime = oCtrler.MtdGetDate();
                    oEvent.IsDelete = false;
                    oEvent.IsArchived = false;
                    MtdGetControlValues(oEvent);
                    oCtrler.OLinqData.TblSDCEvents.InsertOnSubmit(oEvent);
                    oCtrler.OLinqData.SubmitChanges();
                    lblEventId.Text = oEvent.Id.ToString();
                    // Đưa vào phần tử cuối cùng.
                    TblSDCEvent oEventParent =
                        (from Eves in oCtrler.OLinqData.TblSDCEvents
                         where Eves.IsDelete == false
                         && Eves.Id != oEvent.Id && Eves.ChildId == null
                         && Eves.ModuleDefID == oCtrler.MtdGetModuleDefId((this.Parent.Parent as PortalModuleBase).ModuleId, this.TabId)
                         select Eves).FirstOrDefault();
                    // Nếu danh sách có ít nhất một phần tử.
                    if (oEventParent != null)
                    {
                        oEventParent.ChildId = oEvent.Id;
                        oCtrler.OLinqData.SubmitChanges();
                    }
                }
                // Cập nhật.
                else
                {
                    TblSDCEvent oEvent =
                        (from Eves in oCtrler.OLinqData.TblSDCEvents
                         where Eves.IsDelete == false
                         && Eves.Id.ToString() == lblEventId.Text
                         select Eves).FirstOrDefault();
                    if (oEvent != null)
                    {
                        MtdGetControlValues(oEvent);
                        oCtrler.OLinqData.SubmitChanges();
                    }
                }
                VluSDCEvent.Controller.MtdRedirect(this.Response, (this.Parent.Parent as PortalModuleBase).TabId, "", "Ctr=CtrEventEdit", "mid=" + (this.Parent.Parent as PortalModuleBase).ModuleId);
                //dgrEvent.DataSource = MtdGetEventList();
                //dgrEvent.DataBind();
                //MtdResetControl();
            }
        }

        void cmbCancel_Click(object sender, EventArgs e)
        {
            Controller.MtdRedirect(Response, (this.Parent.Parent as PortalModuleBase).TabId, "", "Ctr=CtrEventList");
        }

        protected void dgrEvent_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            int iId = int.Parse(dgrEvent.DataKeys[e.Item.ItemIndex].ToString());
            switch (e.CommandName)
            {
                case "cmbDelete":
                    {
                        TblSDCEvent oEvent =
                             (from Eves in oCtrler.OLinqData.TblSDCEvents
                              where Eves.IsDelete == false
                              && Eves.Id == iId
                              select Eves).FirstOrDefault();
                        TblSDCEvent oEventParent =
                             (from Eves in oCtrler.OLinqData.TblSDCEvents
                              where Eves.IsDelete == false
                              && Eves.ChildId == iId
                              select Eves).FirstOrDefault();
                        if (oEventParent != null)
                        {
                            oEventParent.ChildId = oEvent.ChildId;
                        }
                        oEvent.ChildId = null;
                        oEvent.IsDelete = true;
                        oCtrler.OLinqData.SubmitChanges();
                        dgrEvent.DataSource = MtdGetEventList();
                        dgrEvent.DataBind();
                        break;
                    }
                case "cmbEdit":
                    {
                        //TblSDCEvent oEvent =
                        //    (from Eves in oCtrler.OLinqData.TblSDCEvents
                        //     where Eves.IsDelete == false
                        //     && Eves.Id == iId
                        //     select Eves).FirstOrDefault();
                        //MtdSetControlValues(oEvent);
                        //lblEventId.Text = oEvent.Id.ToString();
                        VluSDCEvent.Controller.MtdRedirect(this.Response, (this.Parent.Parent as PortalModuleBase).TabId, "", "Ctr=CtrEventEdit", "mid=" + (this.Parent.Parent as PortalModuleBase).ModuleId, "EventId=" + iId.ToString());
                        break;
                    }
                case "cmbMoveUp":
                    {
                        TblSDCEvent oEvent =
                          (from Eves in oCtrler.OLinqData.TblSDCEvents
                           where Eves.IsDelete == false
                           && Eves.Id == iId
                           select Eves).FirstOrDefault();
                        // Lây con.
                        oEvent =
                          (from Eves in oCtrler.OLinqData.TblSDCEvents
                           where Eves.IsDelete == false
                           && Eves.Id == oEvent.ChildId
                           select Eves).FirstOrDefault();
                        if (oEvent != null)
                        {
                            MtdMoveUp(oEvent.Id);
                            dgrEvent.DataSource = MtdGetEventList();
                            dgrEvent.DataBind();
                        }
                        break;
                    }
                case "cmbMoveDown":
                    {
                        MtdMoveUp(iId);
                        dgrEvent.DataSource = MtdGetEventList();
                        dgrEvent.DataBind();
                        break;
                    }
                default:
                    {
                        dgrEvent.DataSource = MtdGetEventList();
                        dgrEvent.DataBind();
                        break;
                    }
            }
        }

        protected void dgrEvent_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.DataItem != null)
            {
                int iId = int.Parse(dgrEvent.DataKeys[e.Item.ItemIndex].ToString());
                int iModuleDefId = oCtrler.MtdGetModuleDefId((this.Parent.Parent as PortalModuleBase).ModuleId, this.TabId);
                // lay con.
                TblSDCEvent oEvent = oCtrler.OLinqData.TblSDCEvents.Where(ev => ev.IsDelete == false && ev.Id == iId && ev.ModuleDefID == iModuleDefId).FirstOrDefault();
                if (oEvent.ChildId == null)
                {
                    e.Item.FindControl("cmbMoveUp").Visible = false;
                }
                // lay cha.
                oEvent = oCtrler.OLinqData.TblSDCEvents.Where(ev => ev.IsDelete == false && ev.ChildId == oEvent.Id && ev.ModuleDefID == iModuleDefId).FirstOrDefault();
                if (oEvent == null)
                {
                    e.Item.FindControl("cmbMoveDown").Visible = false;
                }
            }
        }
        #endregion Dotnet Methods --------------------------------------
    }
}